package com.zx.zxapiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.zx.zxapiclientsdk.model.Api;
import com.zx.zxapiclientsdk.utils.SignUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 调用api的客户端
 *
 * @author 张旭
 * @version 1.0
 */
public class ZxAPIClient {
    private Integer appId;
    private String accessKey;
    private String secretKey;

    //todo
    public static final String GATEWAY_HOST = "http://{IP地址}:{网关端口号}/api/interface";

    public ZxAPIClient(Integer appId, String accessKey, String secretKey) {
        this.appId = appId;
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public String getResult(Api api) {
        Object body = api.getBody();
        String json = null;
        //对请求参数为空的接口参数进行处理
        if (body == null) {
            body = "";
        }
        json = JSONUtil.toJsonStr(body);
        if ("get".equals(api.getMethod()) || "GET".equals(api.getMethod())) {
            return HttpRequest.get(GATEWAY_HOST)
                    .header("Accept", "application/json;charset=UTF-8")
                    .addHeaders(getHeaderMap(api.getUrl(), api.getInterfaceId(), json, api.getId(), api.getUserAccount()))
                    .charset("UTF-8")
                    .timeout(10000)
                    .body(json)
                    .execute().body();
        } else {
            return HttpRequest.post(GATEWAY_HOST)
                    .header("Accept", "application/json;charset=UTF-8")
                    .addHeaders(getHeaderMap(api.getUrl(), api.getInterfaceId(), json, api.getId(), api.getUserAccount()))
                    .charset("UTF-8")
                    .timeout(10000)
                    .body(json)
                    .execute().body();
        }
    }


    private Map<String, String> getHeaderMap(String url, String interfaceId, String body, Long userId, String userAccount) {
        Map<String, String> headers = new HashMap();
        headers.put("userId", String.valueOf(userId));
        headers.put("userAccount", userAccount);
        headers.put("interfaceId", interfaceId);
        headers.put("url", url);
        headers.put("appId", String.valueOf(appId));

        headers.put("accessKey", accessKey);
        //secretKey不能传输
        headers.put("nonce", RandomUtil.randomNumbers(4));
        headers.put("body", body);
        headers.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        headers.put("sign", SignUtils.getSign(body, secretKey));
        return headers;
    }

}
